package com.lichong.quartzdemo.job.configure;

import com.lichong.quartzdemo.job.entity.TbJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务
 *
 * @author lichong
 */
@Slf4j
public class ScheduleJob implements Job {

    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    public void execute(JobExecutionContext context) {

        TbJob scheduleJob = (TbJob) context.getJobDetail().getJobDataMap().get(TbJob.JOB_PARAM_KEY);

        long startTime = System.currentTimeMillis();

        try {
            // 执行任务
            log.info("任务准备执行，任务ID：{}", scheduleJob.getJobId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(),
                    scheduleJob.getParams());
            Future<?> future = service.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            log.info("任务执行完毕，任务ID：{} 总共耗时：{} 毫秒", scheduleJob.getJobId(), times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);
        }
    }
}
